package cn.itcast.netty.c2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * EventLoop 处理 io 任务
 */
@Slf4j
public class EventLoopIO {
    public static void main(String[] args) {
        //细分2
        EventLoopGroup group = new DefaultEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                //细分1：boss 只负责ServerSocketChannel上的accept事件，work只负责socketChannel上的读写；boss的NioEventLoopGroup 不需要指定线程数，因为只有一个serverSocketChannel
                .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
//                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf by = (ByteBuf) msg;
                                log.debug(by.toString(Charset.defaultCharset()));
                                ctx.fireChannelRead(msg); //将msg传递给下一个handler
                            }
                        }).addLast(group,"handler2",new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf by = (ByteBuf) msg;
                                log.debug(by.toString(Charset.defaultCharset()));
                            }
                        })

                        ;
                    }
                })
                .bind(8080);
    }
}
